#!/bin/bash
# author tyb
# date 20240220

# 执行结果判断函数
function isgreen() {
    if [ $? -eq 0 ]; then
        echo -e "\e[32m$1==========>succeed\e[0m"
    else
        echo -e "\e[31m$1==========>failed\e[0m"
        # exit 1
    fi
}

# 帮助命令函数
function print_help() {
  echo "Usage: $0 [OPTIONS]"
  echo "Options:"
  echo "  --help            Display this help message."
  echo "  --disk,-d         Specify test disk name. Required"
  echo "  --options,-o      Specify test option. default:all"

}

# 收集变量
while [[ $# -gt 0 ]]; do
  case "$1" in
    --help)
       print_help
        exit 0
        ;;
    --disk|-d)
      if [[ -n "$2" ]]; then
        disk_name="$2"
        shift 2
      else
        echo "Missing argument for --help option."
        exit 1
      fi
      ;;
    --options|-o)
      if [[ -n "$2" ]]; then
        options="$2"
        shift 2
      else
        echo "Missing argument for --help option."
        exit 1
      fi
      ;;
    *)
      echo "Invalid option: $1"
      exit 1
      ;;
  esac
done

# 变量收集
disk="$disk_name"
option="${options:-all}"

# 判断fio是否安装

# 判断磁盘是否存在
if lsblk | grep -q /dev/"$disk"; then
    echo -e "\e[31m不存在磁盘: $disk\e[0m"
    exit 1
fi

# 功能函数
# 随机写
function randwrite() {
    echo "/dev/$1 随机写测试"
    echo -e "\e[32m==========================$1 randwrite==========================\e[0m" >> ./disk_test_"$1" 2>&1
    fio -direct=1 -iodepth=10 -rw=randwrite -ioengine=libaio -bs=4k -size=10G -numjobs=15 -group_reporting -filename=/dev/"$1" -name=Rand_Write_Latency_Testing --runtime=60s >> ./disk_test_"$1" 2>&1
    isgreen "$1-randwrite"
}

# 随机读
function randread() {
    echo "/dev/$1 随机读测试"
    echo -e "\e[32m==========================$1 randread==========================\e[0m" >> ./disk_test_"$1" 2>&1
    fio -direct=1 -iodepth=10 -rw=randread -ioengine=libaio -bs=4k -size=10G -numjobs=15  -group_reporting -filename=/dev/"$1" -name=Rand_Read_Testing  -runtime=60s >> ./disk_test_"$1" 2>&1
    isgreen "$1-randread"
}

# 顺序写
function oder_write() {
    echo "/dev/$1 顺序写测试"
    echo -e "\e[32m==========================$1 write==========================\e[0m" >> ./disk_test_"$1" 2>&1
    fio -direct=1 -iodepth=10 -rw=write -ioengine=libaio -bs=4M -size=10G -numjobs=15 -group_reporting -filename=/dev/"$1" -name=Write_Testing  --runtime=60s >> ./disk_test_"$1" 2>&1
    isgreen "$1-write"
}

# 顺序读
function oder_read() {
    echo "/dev/$1 顺序读测试"
    echo -e "\e[32m==========================$1 read==========================\e[0m" >> ./disk_test_"$1" 2>&1
    fio -direct=1 -iodepth=10 -rw=read -ioengine=libaio -bs=4M -size=10G -numjobs=15  -group_reporting -filename=/dev/"$1" -name=Read_Testing  --runtime=60s >> ./disk_test_"$1" 2>&1
    isgreen "$1-read"
}




if [ "$option" == "all" ];then
    randwrite "$disk"
    randread "$disk"
    oder_write "$disk"
    oder_read "$disk"
fi


echo "测试结果请查看: ./disk_test_$disk"
